<!-- 多媒体资料列 -->
<el-table-column label="多媒体资料" align="center">
  <template #default="scope">
    <el-space>
      <template v-if="scope.row.images && scope.row.images.length > 0">
        <el-button 
          type="primary" 
          link
          @click="handlePreviewImages(scope.row.images)"
        >
          图片({{ scope.row.images.length }})
        </el-button>
      </template>
      <template v-if="scope.row.videos && scope.row.videos.length > 0">
        <el-button
          type="success"
          link
          @click="handlePreviewVideos(scope.row.videos)"
        >
          视频({{ scope.row.videos.length }})
        </el-button>
      </template>
      <template v-if="(!scope.row.images || scope.row.images.length === 0) && (!scope.row.videos || scope.row.videos.length === 0)">
        <span>暂无资料</span>
      </template>
    </el-space>
  </template>
</el-table-column>

<!-- 图片预览对话框 -->
<el-dialog v-model="previewVisible" title="图片预览" width="800px">
  <el-carousel height="400px">
    <el-carousel-item v-for="(url, index) in previewImages" :key="index">
      <el-image
        :src="getFullImageUrl(url)"
        fit="contain"
        style="width: 100%; height: 100%"
      />
    </el-carousel-item>
  </el-carousel>
</el-dialog>

<!-- 视频预览对话框 -->
<el-dialog v-model="videoPreviewVisible" title="视频预览" width="800px">
  <div v-for="(url, index) in previewVideos" :key="index" class="video-preview-item">
    <video
      :src="getFullImageUrl(url)"
      controls
      style="width: 100%"
    ></video>
  </div>
</el-dialog>

<!-- 添加或修改非遗信息对话框 -->
<el-dialog :title="title" v-model="open" width="800px" append-to-body>
  <el-form ref="heritageForm" :model="form" :rules="rules" label-width="100px">
    <!-- ... 其他表单项保持不变 ... -->

    <!-- 添加多媒体资料上传部分 -->
    <el-divider content-position="left">多媒体资料</el-divider>
    <el-row>
      <el-col :span="24">
        <el-form-item label="图片资料" prop="images">
          <el-upload
            v-model:file-list="imageList"
            :action="uploadImgUrl"
            list-type="picture-card"
            :headers="headers"
            :before-upload="beforeUpload"
            :on-success="handleImgSuccess"
            :on-remove="handleImgRemove"
            multiple
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">支持jpg/png文件，且不超过5MB</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-form-item label="视频资料" prop="videos">
          <el-upload
            v-model:file-list="videoList"
            :action="uploadVideoUrl"
            :headers="headers"
            :before-upload="beforeVideoUpload"
            :on-success="handleVideoSuccess"
            :on-remove="handleVideoRemove"
            multiple
          >
            <el-button type="primary">上传视频</el-button>
            <template #tip>
              <div class="el-upload__tip">支持mp4格式视频，且不超过50MB</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <template #footer>
    <div class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </template>
</el-dialog>

<script setup name="Heritage">
import { getCurrentInstance, ref, reactive, toRefs } from 'vue';
import { useBaseApi } from '@/hooks/web/useBaseApi';
import { Plus } from '@element-plus/icons-vue';
import { getToken } from "@/utils/auth";

const { proxy } = getCurrentInstance();
const { baseURL } = useBaseApi();

// 表单数据
const data = reactive({
  form: {
    heritageId: undefined,
    heritageName: undefined,
    heritageCode: undefined,
    categoryId: undefined,
    level: undefined,
    description: undefined,
    history: undefined,
    inheritanceStatus: undefined,
    area: undefined,
    images: [], // 初始化为空数组
    videos: []  // 初始化为空数组
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    heritageName: undefined,
    heritageCode: undefined,
    categoryId: undefined,
    level: undefined,
    area: undefined
  },
  rules: {
    heritageName: [
      { required: true, message: "非遗名称不能为空", trigger: "blur" }
    ],
    heritageCode: [
      { required: true, message: "非遗编号不能为空", trigger: "blur" }
    ],
    categoryId: [
      { required: true, message: "所属类别不能为空", trigger: "change" }
    ],
    level: [
      { required: true, message: "级别不能为空", trigger: "change" }
    ]
  }
});

const { form, queryParams, rules } = toRefs(data);

// 其他变量
const uploadImgUrl = ref(import.meta.env.VITE_APP_BASE_API + "/system/heritage/upload/image");
const uploadVideoUrl = ref(import.meta.env.VITE_APP_BASE_API + "/system/heritage/upload/video");
const headers = ref({ Authorization: "Bearer " + getToken() });
const imageList = ref([]);
const videoList = ref([]);
const open = ref(false);
const title = ref("");
const loading = ref(true);
const heritageList = ref([]);
const total = ref(0);

// 预览相关的变量
const previewVisible = ref(false);
const previewImages = ref([]);
const videoPreviewVisible = ref(false);
const previewVideos = ref([]);

// 预览处理函数
function handlePreviewImages(images) {
  if (!Array.isArray(images)) {
    console.warn('图片数据不是数组:', images);
    return;
  }
  if (images.length === 0) {
    proxy.$modal.msgInfo('暂无图片');
    return;
  }
  previewImages.value = images;
  previewVisible.value = true;
}

function handlePreviewVideos(videos) {
  if (!Array.isArray(videos)) {
    console.warn('视频数据不是数组:', videos);
    return;
  }
  if (videos.length === 0) {
    proxy.$modal.msgInfo('暂无视频');
    return;
  }
  previewVideos.value = videos;
  videoPreviewVisible.value = true;
}

// 用于获取完整URL的函数
function getFullImageUrl(url) {
  if (!url) return '';
  // 如果URL已经是完整的URL（以http或https开头），则直接返回
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url;
  }
  // 处理相对路径
  return baseURL + '/' + url;
}

/** 查询非遗信息列表 */
function getList() {
  loading.value = true;
  listHeritage(queryParams.value).then(response => {
    console.log('原始响应数据:', response);
    if (response.code === 200) {
      // 处理每个项目的图片和视频数组
      heritageList.value = response.rows.map(item => {
        console.log('处理前的项目数据:', item);
        
        // 处理图片数组
        let images = [];
        if (item.images) {
          console.log('原始图片数据:', item.images, '类型:', typeof item.images);
          if (typeof item.images === 'string') {
            images = item.images.split(',');
          } else if (Array.isArray(item.images)) {
            images = [...item.images];
          }
          images = images.filter(url => url && url.trim() !== '' && url !== 'null');
          console.log('处理后的图片数组:', images);
        }

        // 处理视频数组
        let videos = [];
        if (item.videos) {
          console.log('原始视频数据:', item.videos, '类型:', typeof item.videos);
          if (typeof item.videos === 'string') {
            videos = item.videos.split(',');
          } else if (Array.isArray(item.videos)) {
            videos = [...item.videos];
          }
          videos = videos.filter(url => url && url.trim() !== '' && url !== 'null');
          console.log('处理后的视频数组:', videos);
        }

        const processedItem = {
          ...item,
          images,
          videos
        };
        console.log('处理后的完整项目数据:', processedItem);
        return processedItem;
      });
      
      console.log('最终的列表数据:', heritageList.value);
      total.value = response.total;
    } else {
      proxy.$modal.msgError(response.msg || '获取列表失败');
    }
    loading.value = false;
  }).catch(error => {
    console.error('获取列表失败:', error);
    loading.value = false;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["heritageForm"].validate(valid => {
    if (valid) {
      console.log('表单验证通过，开始处理数据');
      
      // 确保images和videos字段是数组
      form.value.images = Array.isArray(form.value.images) ? form.value.images : [];
      form.value.videos = Array.isArray(form.value.videos) ? form.value.videos : [];

      // 过滤掉无效的URL
      form.value.images = form.value.images.filter(url => url && url.trim() !== '' && url !== 'null');
      form.value.videos = form.value.videos.filter(url => url && url.trim() !== '' && url !== 'null');
      
      console.log('处理后的表单数据:', {
        images: form.value.images,
        videos: form.value.videos
      });

      if (form.value.heritageId != undefined) {
        updateHeritage(form.value).then(response => {
          console.log('更新响应:', response);
          if (response.code === 200) {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          } else {
            proxy.$modal.msgError(response.msg || "修改失败");
          }
        });
      } else {
        addHeritage(form.value).then(response => {
          console.log('添加响应:', response);
          if (response.code === 200) {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          } else {
            proxy.$modal.msgError(response.msg || "新增失败");
          }
        });
      }
    }
  });
}

/** 图片上传成功的处理 */
function handleImgSuccess(response, file) {
  console.log('图片上传响应:', response);
  
  if (response.code === 200) {
    // 确保form.value.images是一个数组
    form.value.images = Array.isArray(form.value.images) ? form.value.images : [];
    
    // 添加新的图片URL
    const imageUrl = response.data;
    console.log('新的图片URL:', imageUrl);
    
    if (imageUrl && !form.value.images.includes(imageUrl)) {
      form.value.images.push(imageUrl.replace(/^\//, ''));
      console.log('当前图片列表:', form.value.images);
    }
  } else {
    proxy.$modal.msgError(response.msg || '上传失败');
  }
}

/** 视频上传成功的处理 */
function handleVideoSuccess(response, file) {
  console.log('视频上传响应:', response);
  
  if (response.code === 200) {
    // 确保form.value.videos是一个数组
    form.value.videos = Array.isArray(form.value.videos) ? form.value.videos : [];
    
    // 添加新的视频URL
    const videoUrl = response.data;
    console.log('新的视频URL:', videoUrl);
    
    if (videoUrl && !form.value.videos.includes(videoUrl)) {
      form.value.videos.push(videoUrl.replace(/^\//, ''));
      console.log('当前视频列表:', form.value.videos);
    }
  } else {
    proxy.$modal.msgError(response.msg || '上传失败');
  }
}

/** 图片移除的处理 */
function handleImgRemove(file) {
  if (!Array.isArray(form.value.images)) {
    form.value.images = [];
    return;
  }
  
  const fileUrl = file.response?.data || file.url;
  if (fileUrl) {
    const index = form.value.images.findIndex(url => url === fileUrl);
    if (index > -1) {
      form.value.images.splice(index, 1);
      console.log('移除后的图片列表:', form.value.images);
    }
  }
}

/** 视频移除的处理 */
function handleVideoRemove(file) {
  if (!Array.isArray(form.value.videos)) {
    form.value.videos = [];
    return;
  }
  
  const fileUrl = file.response?.data || file.url;
  if (fileUrl) {
    const index = form.value.videos.findIndex(url => url === fileUrl);
    if (index > -1) {
      form.value.videos.splice(index, 1);
      console.log('移除后的视频列表:', form.value.videos);
    }
  }
}

/** 表单重置 */
function reset() {
  form.value = {
    heritageId: undefined,
    heritageName: undefined,
    heritageCode: undefined,
    categoryId: undefined,
    level: undefined,
    description: undefined,
    history: undefined,
    inheritanceStatus: undefined,
    area: undefined,
    images: [], // 确保初始化为空数组
    videos: []  // 确保初始化为空数组
  };
  imageList.value = [];
  videoList.value = [];
  proxy.resetForm("heritageForm");
}

// 初始化
getList();
</script>

<style scoped>
.video-preview-item {
  margin-bottom: 20px;
}

.video-preview-item:last-child {
  margin-bottom: 0;
}
</style> 